package com.waymap.service.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.alibaba.fastjson.JSONArray;
import com.waymap.domain.*;
import com.waymap.utils.SyncInvertoryService;
import javafx.concurrent.Task;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.reflections.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.waymap.mapper.ItemInventorysMapper;
import com.waymap.mapper.ItemsMapper;
import com.waymap.mapper.LocationsMapper;
import com.waymap.mapper.TransactionItemInventoryDetailsMapper;
import com.waymap.mapper.TransactionItemsMapper;
import com.waymap.mapper.TransactionsMapper;
import com.waymap.service.TransactionInventoryDetailsService;
import com.waymap.service.UserService;
import com.waymap.utils.CommonEnum;
import com.waymap.utils.CommonService;

@Service
@Slf4j
public class TransactionInventoryDetailsServiceImpl extends BaseService<TransactionItems> implements TransactionInventoryDetailsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private TransactionItemsMapper transactionItemsMapper;
    @Resource
    private TransactionItemInventoryDetailsMapper transactionItemInventoryDetailMapper;
    @Resource
    private TransactionsMapper transactionsMapper;
    @Resource
    private LocationsMapper locationsMapper;
    @Resource
    private ItemsMapper itemsMapper;
    @Autowired
    private UserService userService;
    @Resource
    private ItemInventorysMapper itemInventorysMapper;
    @Resource
    private CommonService commonService;
    @Resource
    private SyncInvertoryService syncInvertoryService;


    /**
     * 同步locations数据到NS syncLocationsFromNS
     *
     * @param json
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map> syncLocationsFromNS(String json) {
        Map<String, Object> map = new HashMap(16);
        Locations locations = new Locations();
        JSONObject jsonObject = JSONObject.parseObject(json);
        if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
            locations.setAccountId(jsonObject.getString("accountId"));
        }
        if (!Utils.isEmpty(jsonObject.getString("location_id"))) {
            locations.setLocationId(Integer.valueOf(jsonObject.getString("location_id")));
        }
        int checkExist = locationsMapper.selectCount(locations);
        if (checkExist > 0) {
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "同步数据成功，仓库已存在");
        } else {
            if (!Utils.isEmpty(jsonObject.getString("location_name"))) {
                locations.setLocationName(jsonObject.getString("location_name"));
            }
            locations.setAvailable("Y");
            locationsMapper.insert(locations);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "同步数据成功，新仓库写入成功");
        }
        return ResponseEntity.ok(map);
    }

    /**
     * 修改拣选框到NS syncSOWaveFromNS
     *
     * @param json
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map> syncSOWaveFromNS(String json) {
        Map<String, Object> map = new HashMap(16);
        Transactions transactions = new Transactions();
        JSONObject jsonObject = JSONObject.parseObject(json);
        if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
            transactions.setAccountId(jsonObject.getString("accountId"));
        }
        if (!Utils.isEmpty(jsonObject.getString("name"))) {
            transactions.setTranid(jsonObject.getString("name"));
        }
        Transactions transactions1 = transactionsMapper.selectOne(transactions);
        transactions1.setPickup(null);
        transactionsMapper.updateByPrimaryKey(transactions1);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", "解绑成功");
        return ResponseEntity.ok(map);
    }

    @Override
    public ResponseEntity<Map> deleteSOFromNS(String json) {
        Map<String, Object> map = new HashMap(16);
        Transactions transactions = new Transactions();
        JSONObject jsonObject = JSONObject.parseObject(json);
        if (!Utils.isEmpty(jsonObject.getString("tranid"))) {
            transactions.setTranid(jsonObject.getString("tranid"));
        }
        if (!Utils.isEmpty(jsonObject.getString("trackingNumber"))) {
            transactions.setTrackingNumber(jsonObject.getString("trackingNumber"));
        }
        if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
            transactions.setAccountId(jsonObject.getString("accountId"));
        }
        if (transactionsMapper.delete(transactions) > 0) {
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "删除成功");
        } else {
            map.put("status", CommonEnum.value("eFail"));
            map.put("msg", "删除失败");
        }
        return ResponseEntity.ok(map);
    }

    /**
     * 同步items数据到NS syncItemsFromNS
     *
     * @param json
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map> syncItemsFromNS(String json) {
        Map<String, Object> map = new HashMap(16);
        Items items = new Items();
        JSONObject jsonObject = JSONObject.parseObject(json);
        if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
            items.setAccountId(jsonObject.getString("accountId"));
        }
        if (!Utils.isEmpty(jsonObject.getString("internalid"))) {
            items.setItemId(Integer.valueOf(jsonObject.getString("internalid")));
        }
        List<Items> itemList = itemsMapper.select(items);
        if (itemList.size() > 0) {
            items = itemList.get(0);
            Items editIitems = new Items();
            editIitems.setItemId(items.getItemId());
            editIitems.setAccountId(items.getAccountId());
            if (!Utils.isEmpty(jsonObject.getString("upccode"))) {
                editIitems.setUpc(jsonObject.getString("upccode"));
            }
            if (!Utils.isEmpty(jsonObject.getString("name"))) {
                editIitems.setItemName(jsonObject.getString("name"));
            }
            if (!Utils.isEmpty(jsonObject.getString("displayname"))) {
                editIitems.setItemDescription(jsonObject.getString("displayname"));
            }
            if (!Utils.isEmpty(jsonObject.getString("itemType"))) {
                editIitems.setItemType(jsonObject.getString("itemType"));
            }
            itemsMapper.updateItem(editIitems);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "同步数据成功,产品已存在");
        } else {
            if (!Utils.isEmpty(jsonObject.getString("upccode"))) {
                items.setUpc(jsonObject.getString("upccode"));
            }
            if (!Utils.isEmpty(jsonObject.getString("name"))) {
                items.setItemName(jsonObject.getString("name"));
            }
            if (!Utils.isEmpty(jsonObject.getString("displayname"))) {
                items.setItemDescription(jsonObject.getString("displayname"));
            }
            if (!Utils.isEmpty(jsonObject.getString("itemType"))) {
                items.setItemType(jsonObject.getString("itemType"));
            }

            items.setCreationDate(new Date());
            itemsMapper.insert(items);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "同步数据成功,产品信息写入成功");
        }

        return ResponseEntity.ok(map);
    }

    /**
     * 同步transactions和transaction_inventory_details数据到NS saveTrancationSyncData
     *
     * @param json
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map> syncTrancationData(String json) {

        Map<String, Object> map = new HashMap(16);
        Map<String, Object> param = new HashMap(16);
        Transactions tranVo = new Transactions();
        JSONObject jsonObject = JSONObject.parseObject(json);
        String accountId = null;
        int location = -1;
        String transType = null;
        boolean flag = false;
        if (!Utils.isEmpty(jsonObject.getString("tranid"))) {
            param.put("tranid", jsonObject.getString("tranid"));
            tranVo.setTranid(jsonObject.getString("tranid"));
        }
        if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
            accountId = jsonObject.getString("accountId");
            tranVo.setAccountId(jsonObject.getString("accountId"));
        }

        //帕拓逊收货计划修改
        if ("ITEM_RECEIPT_PLAN".equals(jsonObject.getString("transactionType"))) {
            Transactions transactions=transactionsMapper.selectOne(tranVo);
            if (transactions != null) {
                transactions.setStatus("PENDING");
                transactions.setCreatedBy("SYNC");
                transactions.setLastUpdateBy("SYNC");
                transactions.setSyncToNs("N");
                transactions.setErrorReason("null");
                transactions.setNum(0);
                transactions.setLockedByUser("0");
                if (!Utils.isEmpty(jsonObject.getString("locationId"))) {
                    location = Integer.parseInt(jsonObject.getString("locationId"));
                    transactions.setLocationId(location);
                }
                if (!Utils.isEmpty(jsonObject.getString("locationName"))) {
                    transactions.setLocationName(jsonObject.getString("locationName"));
                }
                transactionsMapper.updateByPrimaryKey(transactions);
                String tranDetails = jsonObject.getString("transaction_inventory_details");
                com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(tranDetails);
                for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) {
                    TransactionItems ti = new TransactionItems();
                    JSONObject obj = (JSONObject) iterator.next();
                    if (null != obj.get("transactionId")) {
                        ti.setTransactionId(obj.get("transactionId").toString());
                    }
                    ti.setAccountId(accountId);
                    if (null != obj.get("itemId")) {
                        ti.setItemId(Integer.parseInt(obj.get("itemId").toString()));
                    }
                    TransactionItems transactionItems = transactionItemsMapper.selectOne(ti);
                    if (null != obj.get("quantity")) {
                        transactionItems.setQuantity(Integer.parseInt(obj.get("quantity").toString()));
                    }
                    transactionItems.setQuantityReceived(0);
                    int primaryKey = transactionItemsMapper.updateByPrimaryKey(transactionItems);
                    if (primaryKey > 0) {
                        map.put("status", CommonEnum.value("eSuccess"));
                        map.put("msg", "修改收货计划数量成功");
                    } else {
                        map.put("status", CommonEnum.value("eFail"));
                        map.put("msg", "修改收货计划数量失败");
                    }
                    return ResponseEntity.ok(map);
                }
            }
        }

        if (transactionsMapper.selectOne(tranVo) == null) {
            if (!Utils.isEmpty(jsonObject.getString("transactionType"))) {
                transType = jsonObject.getString("transactionType");
                tranVo.setTransactionType(transType);
            }
            if (null != jsonObject.get("createdFrom")) {
                tranVo.setCreatedFrom(jsonObject.getString("createdFrom").trim());
            }
            if (!Utils.isEmpty(jsonObject.getString("nsInternalid"))) {
                tranVo.setNsInternalid(Integer.parseInt(jsonObject.getString("nsInternalid")));
            }
            if (!Utils.isEmpty(jsonObject.getString("status"))) {
                tranVo.setStatus(jsonObject.getString("status"));
            }
            if (!Utils.isEmpty(jsonObject.getString("status1"))) {
                tranVo.setStatus1(jsonObject.getString("status1"));
            }
            if (!Utils.isEmpty(jsonObject.getString("pickup"))) {
                tranVo.setPickup(jsonObject.getString("pickup"));
            }
            if (!Utils.isEmpty(jsonObject.getString("trackingNumber"))) {
                tranVo.setTrackingNumber(jsonObject.getString("trackingNumber"));
            }
            if (!Utils.isEmpty(jsonObject.getString("locationId"))) {
                location = Integer.parseInt(jsonObject.getString("locationId"));
                tranVo.setLocationId(location);
            }
            if (!Utils.isEmpty(jsonObject.getString("locationName"))) {
                tranVo.setLocationName(jsonObject.getString("locationName"));
            }

            if (!Utils.isEmpty(jsonObject.getString("toLocationId"))) {
                tranVo.setToLocationId(Integer.parseInt(jsonObject.getString("toLocationId")));
            }
            if (!Utils.isEmpty(jsonObject.getString("toLocationName"))) {
                tranVo.setToLocationName(jsonObject.getString("toLocationName"));
            }
            tranVo.setCreatedBy("SYNC");
            tranVo.setLastUpdateBy("SYNC");
            tranVo.setSyncToNs("N");
            tranVo.setErrorReason("null");
            tranVo.setNum(0);
            tranVo.setLockedByUser("0");
//            System.out.println(tranVo);
            transactionsMapper.insert(tranVo);
//            int count = transactionsMapper.insertTransactions(tranVo);
            logger.info("*****************同步Transactions成功*******************");
            String tranDetails = jsonObject.getString("transaction_inventory_details");
            if (!Utils.isEmpty(tranDetails)) {
                com.alibaba.fastjson.JSONArray jsonArray = JSONObject.parseArray(tranDetails);
                for (Iterator iterator = jsonArray.iterator(); iterator.hasNext(); ) {
                    TransactionItems ti = new TransactionItems();
                    JSONObject obj = (JSONObject) iterator.next();
                    if (null != obj.get("transactionId")) {
                        ti.setTransactionId(obj.get("transactionId").toString());
                    }
                    ti.setAccountId(accountId);
                    if (null != obj.get("itemId")) {
                        ti.setItemId(Integer.parseInt(obj.get("itemId").toString()));
                    }
                    if (transactionItemsMapper.selectOne(ti) == null) {
                        if (null != obj.get("platform")) {
                            ti.setPlatform(obj.get("platform").toString());
                        }
                        if (null != obj.get("orderNumber")) {
                            ti.setOrderNumber(obj.get("orderNumber").toString());
                        }

                        if (null != obj.get("lotNumber")) {
                            ti.setLotNumber(obj.get("lotNumber").toString());
                        }
                        if (null != obj.get("binId")) {
                            ti.setBinId(Integer.parseInt(obj.get("binId").toString()));
                        }
                        if (null != obj.get("binNumber")) {
                            ti.setBinNumber(obj.get("binNumber").toString());
                        }
                        if (null != obj.get("toBinId")) {
                            ti.setToBinId(Integer.parseInt(obj.get("toBinId").toString()));
                        }
                        if (null != obj.get("toBinNumber")) {
                            ti.setToBinNumber(obj.get("toBinNumber").toString());
                        }

                        if (null != obj.get("quantity")) {
                            ti.setQuantity(Integer.parseInt(obj.get("quantity").toString()));
                        }
                        if (null != obj.get("quantityReceived")) {
                            ti.setQuantityReceived(Integer.parseInt(obj.get("quantityReceived").toString()));
                        } else {
                            ti.setQuantityReceived(0);
                        }
                        if (null != obj.get("quantityFulfilled")) {
                            ti.setQuantityFulfilled(Integer.parseInt(obj.get("quantityFulfilled").toString()));
                        } else {
                            ti.setQuantityFulfilled(0);
                        }
                        ti.setQuantityScaned(0);
                        transactionItemsMapper.insert(ti);
                        logger.info("*****************同步TransactionItems成功*******************");
                        //上架任务完成QC时会发生移库，将库存变化同步过来
                        if ("BIN_TRANSFER_TASK".equals(transType)) {
                            // commonService.updateItemInventory(location, Integer.parseInt((String) obj.get("itemId")), accountId, (String) obj.get("binNumber"), (String) obj.get("lotNumber"), -Integer.parseInt((String) obj.get("quantity")));
                            // commonService.updateItemInventory(location, Integer.parseInt((String) obj.get("itemId")), accountId, (String) obj.get("toBinNumber"), (String) obj.get("lotNumber"), Integer.parseInt((String) obj.get("quantity")));
                            logger.info("*****************同步移库库存成功*******************");
                        }
                        map.put("status", CommonEnum.value("eSuccess"));
                        map.put("msg", "同步数据成功");
                    } else {
                        logger.info("*****************单据行已存在，不再重复写入*******************");
                        flag = true;
                    }
                }
            } else {
                if ("SO_AND_CARRIER".equals(transType)) {
                    map.put("status", CommonEnum.value("eSuccess"));
                    map.put("msg", "同步数据成功");
                } else {
                    map.put("status", CommonEnum.value("eFail"));
                    map.put("msg", "缺失单据行信息");
                }
            }
        } else {
            logger.info("*****************此数据已经同步，不能再次同步*******************");
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "此数据已经同步，不能再次同步");
        }
        if (flag) {
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "同步数据成功，存在已存在的单据行，不会重复写入");
        }
        return ResponseEntity.ok(map);

    }

    /**
     * 查询TRACKING_NUMBER详情
     *
     * @param param
     * @return
     */
    @Override
    public List<Map<String, Object>> queryTransactionInventoryDetailList(Map<String, Object> param) {
        return transactionItemsMapper.queryTransactionInventoryDetailList(param);
    }

    @Override
    public List<TransactionItemInventoryDetails> selectTrans(TransactionItemInventoryDetails transactionItemInventoryDetails) {
        return transactionItemInventoryDetailMapper.select(transactionItemInventoryDetails);
//        return transactionItemInventoryDetailMapper.selectOne(transactionItemInventoryDetails);
    }

    @Override
    public ResponseEntity<Map> syncItemInventoryFromNS(Map itemInv) {
        // TODO Auto-generated method stub
        ItemInventorys o = new ItemInventorys();
        o.setItemId(Integer.parseInt((String) itemInv.get("itemId")));
        o.setLocationId(Integer.parseInt((String) itemInv.get("location")));
        o.setAccountId((String) itemInv.get("accountId"));
        o.setBinName((String) itemInv.get("binNumber"));
        o.setLotNumber((String) itemInv.get("lotNumber"));
        if (itemInv.get("binId") != null && !"".equals(itemInv.get("binId"))) {
            o.setBinId(Integer.parseInt((String) itemInv.get("binId")));
        }
        o.setQuantityAvailable(Integer.parseInt((String) itemInv.get("qtyOnHand")));
        itemInventorysMapper.insert(o);
        Map<String, Object> map = new HashMap(16);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", "数据写入成功");
        return ResponseEntity.ok(map);
    }

    /**
     * @author vincent mai
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map> saveTransationDetailLine(Map transDetail, String userName) {
        Map<String, Object> map = new HashMap(16);
        Transactions tx = new Transactions();
        tx.setAccountId((String) transDetail.get("accountId"));
        tx.setTranid(((String) transDetail.get("transactionId")));
        tx.setTransactionType((String) transDetail.get("transactionType"));
        tx = transactionsMapper.selectOne(tx);
        tx.setLockedByUser(userName);
        transactionsMapper.updateByPrimaryKey(tx);

        TransactionItems transactionItems = new TransactionItems();
        transactionItems.setTransactionId((String) transDetail.get("transactionId"));
        transactionItems.setItemId((Integer) transDetail.get("itemId"));
        transactionItems.setAccountId((String) transDetail.get("accountId"));
        if ("INVENTORY_COUNT".equals(transDetail.get("transactionType"))) {
            transactionItems.setBinNumber((String) transDetail.get("binNumber"));
        }
        TransactionItems transactionItems1 = transactionItemsMapper.selectOne(transactionItems);
        if ("INVENTORY_COUNT".equals(transDetail.get("transactionType"))) {
            transactionItems1.setLineId((Integer) transDetail.get("lineId"));
        }
        if (transDetail.get("lotNumber") != null && ((String) transDetail.get("lotNumber")).length() != 0) {
            transactionItems1.setLotNumber((String) transDetail.get("lotNumber"));
        }

        TransactionItemInventoryDetails invDetail = new TransactionItemInventoryDetails();
        invDetail.setTransactionId((String) transDetail.get("transactionId"));
        invDetail.setItemId((Integer) transDetail.get("itemId"));
        invDetail.setAccountId((String) transDetail.get("accountId"));
        invDetail.setBinNumber((String) transDetail.get("binNumber"));
        invDetail.setToBinNumber((String) transDetail.get("to_bin_number"));
        invDetail.setStatus("PENDING");
        List<TransactionItemInventoryDetails> invDetails = transactionItemInventoryDetailMapper.select(invDetail);

        if (invDetails.size() > 0) {
            TransactionItemInventoryDetails tmp = invDetails.get(0);
            if (!"0".equals(transDetail.get("quantityReceived").toString())) {

                /*判断以前的是多少*/
                transactionItems1.setQuantityScaned(transactionItems1.getQuantityScaned() + (Integer) transDetail.get("quantityReceived") - tmp.getQuantity());
                tmp.setQuantity((Integer) transDetail.get("quantityReceived"));
            } else {
                transactionItems1.setQuantityScaned(transactionItems1.getQuantityScaned() + (Integer) transDetail.get("quantityFulfilled") - tmp.getQuantity());
                tmp.setQuantity((Integer) transDetail.get("quantityFulfilled"));
            }
            transactionItemInventoryDetailMapper.updateByPrimaryKey(tmp);
        } else {
            if (!"0".equals(transDetail.get("quantityReceived").toString())) {
                invDetail.setQuantity((Integer) transDetail.get("quantityReceived"));
                transactionItems1.setQuantityScaned(transactionItems1.getQuantityScaned() + (Integer) transDetail.get("quantityReceived"));
            } else {
                invDetail.setQuantity((Integer) transDetail.get("quantityFulfilled"));
                transactionItems1.setQuantityScaned(transactionItems1.getQuantityScaned() + (Integer) transDetail.get("quantityFulfilled"));

            }
            if (transactionItems1.getLotNumber() != null && (transactionItems1.getLotNumber()).length() != 0) {
                invDetail.setLotNumber(transactionItems1.getLotNumber());
            } else {
                invDetail.setLotNumber(transactionItems1.getPlatform());
            }
            Date d = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateNowStr = sdf.format(d);
            invDetail.setOperateTime(dateNowStr);
            transactionItemInventoryDetailMapper.insert(invDetail);
        }
        //transactionItemsMapper.updateTransationItemLine(transDetail);

        transactionItemsMapper.updateByPrimaryKey(transactionItems1);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", CommonEnum.value("eSMessage"));
        return ResponseEntity.ok(map);
    }

    /**
     * @author vincent mai
     */
    @Override
    public String saveBinTransferDetailLine(Map transDetail) {
        // TODO Auto-generated method stub

        String tranId = (String) transDetail.get("transactionId");
        if (tranId == null || "".equals(tranId)) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
            String dateNowStr = sdf.format(new Date());
            tranId = "BIN_TRANSFER" + dateNowStr;
            Transactions tr = new Transactions();
            tr.setTranid(tranId);
            tr.setTransactionType("BIN_TRANSFER");
            //获取当前AccountId
            if (null != transDetail.get("token")) {
                User user = userService.getUserInfoByToken(transDetail.get("token").toString());
                if (null != user) {
                    tr.setAccountId(user.getAccountId());
                    tr.setCreatedBy(user.getUserName());
                    tr.setLastUpdateBy(user.getUserName());
                }
            }
            tr.setSyncToNs("N");
            transactionsMapper.insert(tr);

        }
        TransactionItems line = new TransactionItems();
        line.setTransactionId(tranId);
        line.setItemId((int) transDetail.get("itemId"));
        line.setQuantity((int) transDetail.get("quantity"));
        line.setQuantityFulfilled(0);
        line.setQuantityReceived(0);
        line.setBinId(Integer.valueOf((String) transDetail.get("binId")));
        line.setToBinId(Integer.valueOf((String) transDetail.get("toBinId")));
        transactionItemsMapper.insert(line);
        return tranId;
    }

    @Override
    public ResponseEntity<Map> syncItemInventoryFromNS(String json) {
        JSONArray objects = JSONArray.parseArray(json);
        int count = 0;
        List<ItemInventorys> itemInventoryslist = new ArrayList<>();
        if (objects.size() > 0) {
            for (int i = 0; i < objects.size(); i++) {
                JSONObject jsonObject = objects.getJSONObject(i);
                ItemInventorys o = new ItemInventorys();
                if (jsonObject.get("itemId").toString().equals("")) {
                    continue;
                }
                o.setItemId(Integer.parseInt((String) jsonObject.get("itemId")));
                o.setLocationId(Integer.parseInt((String) jsonObject.get("location")));
                o.setAccountId((String) jsonObject.get("accountId"));
                o.setBinName((String) jsonObject.get("binNumber"));
                o.setLotNumber((String) jsonObject.get("lotNumber"));
                if (jsonObject.get("binId") != null && !"".equals(jsonObject.get("binId"))) {
                    o.setBinId(Integer.parseInt((String) jsonObject.get("binId")));
                }
                o.setQuantityAvailable(Integer.parseInt((String) jsonObject.get("qtyOnHand")));
                itemInventoryslist.add(o);
                count++;
            }
        }

        itemInventorysMapper.insertCodeBatch(itemInventoryslist);
        logger.info("success 总共同步" + count + "条库存");
        Map<String, Object> map = new HashMap(16);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", "数据写入成功");
        return ResponseEntity.ok(map);
    }

    @Override
    public ResponseEntity<Map> clearItemInventory(String accountId) {
        // TODO Auto-generated method stub
        itemInventorysMapper.deleteAllItemInventory(accountId);
        Map<String, Object> map = new HashMap();
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", "数据删除成功");
        return ResponseEntity.ok(map);
    }


    @Transactional
    @Override
    public ResponseEntity<Map> syncDataFromNS(String json) {
        /**
         * 同步单据  四种场景(syncType)  binsTransfer   adjustInvertory  itemReceipt  itemFulfillment
         *         两种状态(type)      delete create
         */
        Map<String, Object> map = new HashMap(16);
        try {
            net.sf.json.JSONObject jsonObjectToStr = net.sf.json.JSONObject.fromObject(json);
            String syncType = jsonObjectToStr.get("syncType").toString();
            String type = jsonObjectToStr.get("type").toString();
            String tranid = jsonObjectToStr.get("tranid").toString();
            net.sf.json.JSONArray jsonArray = jsonObjectToStr.getJSONArray("alls");
            if (jsonArray.size() < 1) {
                map.put("status", CommonEnum.value("eFail"));
                map.put("msg", "传入数据为空");
                return ResponseEntity.ok(map);
            }

            logger.info("======begin sync  type: " + type + "  " + " syncType:" + syncType + "=========");
            if ("binTransfer".equals(syncType)) {
                syncInvertoryService.binTransfer(jsonArray, syncType, type, tranid);
            } else if ("adjustInvertory".equals(syncType)) {
                syncInvertoryService.adjustInventory(jsonArray, syncType, type, tranid);
            } else if ("itemFulfillment".equals(syncType)) {
                syncInvertoryService.itemFulfill(jsonArray, syncType, type, tranid);
            } else if ("itemReceipt".equals(syncType)) {
                syncInvertoryService.itemReceipt(jsonArray, syncType, type, tranid);
            }else if ("inventoryTransfer".equals(syncType)) {
                syncInvertoryService.inventoryTransfer(jsonArray, syncType, type, tranid);
            }
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "数据修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", CommonEnum.value("eFail"));
            map.put("msg", e.getMessage());
        }
        return ResponseEntity.ok(map);
    }

    @Override
    public ResponseEntity<Map> updateNsWave(String json) {
        Map<String, Object> map = new HashMap(16);
        try {
            Transactions transactions = new Transactions();
            JSONObject jsonObject = JSONObject.parseObject(json);
            String tranid = null;
            String accountId = null;
            if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
                accountId = jsonObject.getString("accountId");
            }
            if (!Utils.isEmpty(jsonObject.getString("tranid"))) {
                tranid = jsonObject.getString("tranid");
            }
            transactions.setAccountId(accountId);
            transactions.setTranid(tranid);
            Transactions transactions1 = transactionsMapper.selectOne(transactions);
            if (transactions1 != null) {
                transactions1.setStatus("PENDING");
                transactions1.setLockedByUser(String.valueOf(0));
                transactionsMapper.updateByPrimaryKey(transactions1);
            }
            TransactionItems transactionItems = new TransactionItems();
            transactionItems.setAccountId(accountId);
            transactionItems.setTransactionId(tranid);
            List<TransactionItems> select = transactionItemsMapper.select(transactionItems);
            if (select.size() > 0) {
                for (TransactionItems transactionItems1 : select) {
                    transactionItems1.setQuantityFulfilled(0);
                    transactionItems1.setQuantityReceived(0);
                    transactionItems1.setQuantityScaned(0);
                    transactionItemsMapper.updateByPrimaryKey(transactionItems1);
                }
            }
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "数据重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", CommonEnum.value("eFail"));
            map.put("msg", e.getMessage());
        }
        return ResponseEntity.ok(map);
    }

    @Override
    public ResponseEntity<Map> updateICstatus(String json) {
        Map<String, Object> map = new HashMap(16);
        try {
            Transactions transactions = new Transactions();
            JSONObject jsonObject = JSONObject.parseObject(json);
            String accountId = null;
            if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
                accountId = jsonObject.getString("accountId");
            }
            transactions.setAccountId(accountId);
            if (!Utils.isEmpty(jsonObject.getString("tranid"))) {
                transactions.setTranid(jsonObject.getString("tranid"));
            }
            if (!Utils.isEmpty(jsonObject.getString("transactionType"))) {
                transactions.setTransactionType(jsonObject.getString("transactionType"));
            }
            Transactions transactions1 = transactionsMapper.selectOne(transactions);
            transactions1.setStatus1(jsonObject.getString("status1"));
            transactionsMapper.updateByPrimaryKey(transactions1);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "数据重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", CommonEnum.value("eFail"));
            map.put("msg", e.getMessage());
        }
        return ResponseEntity.ok(map);
    }

    @Override
    public ResponseEntity<Map> updateWmsError(String json) {
        Map<String, Object> map = new HashMap(16);
        try {
            Transactions transactions = new Transactions();
            JSONObject jsonObject = JSONObject.parseObject(json);
            String accountId = null;
            if (!Utils.isEmpty(jsonObject.getString("accountId"))) {
                accountId = jsonObject.getString("accountId");
            }
            transactions.setAccountId(accountId);
            if (!Utils.isEmpty(jsonObject.getString("tranid"))) {
                transactions.setTranid(jsonObject.getString("tranid"));
            }
            Transactions transactions1 = transactionsMapper.selectOne(transactions);
            transactions1.setErrorReason(jsonObject.getString("error"));
            transactionsMapper.updateByPrimaryKey(transactions1);
            map.put("status", CommonEnum.value("eSuccess"));
            map.put("msg", "数据重置成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("status", CommonEnum.value("eFail"));
            map.put("msg", e.getMessage());
        }
        return ResponseEntity.ok(map);
    }

    @Override
    public ResponseEntity<Map> getScanedNumBybin(String tranid, int itemid) {
        TransactionItemInventoryDetails txDetails = new TransactionItemInventoryDetails();
        txDetails.setItemId(Integer.valueOf(itemid));
        txDetails.setTransactionId(tranid);
        txDetails.setStatus("PENDING");
        List<TransactionItemInventoryDetails> txList = transactionItemInventoryDetailMapper.select(txDetails);
        Map<String, Object> map = new HashMap(16);
        List<BinAndNum> list = new ArrayList();
        if (txList.size() > 0) {
            for (int i = 0; i < txList.size(); i++) {
                BinAndNum binAndNum = new BinAndNum();
                binAndNum.setBinName(txList.get(i).getToBinNumber());
                binAndNum.setQuantity(txList.get(i).getQuantity());
                list.add(binAndNum);
            }
        }
        map.put("data", list);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", CommonEnum.value("eSMessage"));
        return ResponseEntity.ok(map);
    }


}

